//
//  SearchViewController.m
//  iShop
//
//  Created by svp on 18/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchResultViewController.h"
#import "ResourceLoader.h"
#import "TitleTextfieldCell.h"
#import "CoreDataUtils.h"
#import "ZXingWidgetController.h"
#import "QRCodeReader.h"

@implementation SearchViewController

@synthesize tableView = _tableView;
@synthesize seachButton = _seachButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
		condition = [[NSMutableDictionary alloc] init];
		[condition setObject:@"-1" forKey:@"Shop"];
		[condition setObject:@"-1" forKey:@"MainCategory"];
		[condition setObject:@"-1" forKey:@"SubCategory"];
		[condition setObject:@"-1" forKey:@"Brand"];
		[condition setObject:[NSNumber numberWithBool:NO] forKey:@"OnPromo"];
		[condition setObject:@"-1" forKey:@"PriceType"];
		[condition setObject:[NSNumber numberWithInt:0] forKey:@"PriceValue1"];
		[condition setObject:[NSNumber numberWithInt:0] forKey:@"PriceValue2"];
    }
    return self;
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	self.title = @"Search";
	self.navigationItem.rightBarButtonItem = _seachButton;
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
	backButton.title = @"Back";
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
	
	
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditCell)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
}

-(void) endEditCell
{
	[_tableView endEditing:YES];
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, 380);
}

- (void)dealloc {
	NSLog(@"SearchViewController dealloc");
	[_tableView release];
	[_seachButton release];
    [super dealloc];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return condition.count - 3 + ([[condition objectForKey:@"PriceType"] isEqualToString:@"-1"] ? 1 : ([[condition objectForKey:@"PriceType"] isEqualToString:@"2"]? 3 : 2));
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.row > 5) {
		NSLog(@"AAAAAA");
	}
	TitleTextfieldCell* cell = (TitleTextfieldCell*)[tableView dequeueReusableCellWithIdentifier:@"TitleTextfieldCell"];
	if (!cell || indexPath.row > 5) {
		ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TitleTextfieldCell"] autorelease];
		cell = (TitleTextfieldCell*)rc.resource;
		cell.textField.text = @"";
		cell.delegate = self;
		cell.textField.textAlignment = UITextAlignmentRight;		
	}
	cell.textField.keyboardType = UIKeyboardTypeNumberPad;
	cell.textField.hidden = NO;
	cell.titleLabel.text = @"";//[[condition valueForKey:@"PriceType"] isEqualToString:@"2"] ? @"From" : @"Price";
	cell.textField.text = @"";//[[condition valueForKey:@"PriceValue1"] stringValue];
	for(UIView *sv in cell.subviews)
		if ([sv isKindOfClass:[UISwitch class]]) {
			[sv removeFromSuperview];
		}
	
	cell.tag = indexPath.row;
	switch (indexPath.row) {
		case 0:
			cell.titleLabel.text = @"Shop";
			[cell initPickerWithArray:[CoreDataUtils getSearchShopList]];
			[cell setPickerSelectAt:[condition valueForKey:@"Shop"]];
			break;
		case 1:
			cell.titleLabel.text = @"Group Category";
			[cell initPickerWithArray:[CoreDataUtils getSearchMainCategory]];
			[cell setPickerSelectAt:[condition valueForKey:@"MainCategory"]];
			break;
		case 2:
			cell.titleLabel.text = @"Category";
			[cell initPickerWithArray:[CoreDataUtils getSearchSubCategory:[condition valueForKey:@"MainCategory"]]];
			[cell setPickerSelectAt:[condition valueForKey:@"SubCategory"]];
			break;
		case 3:
			cell.titleLabel.text = @"Brand";
			[cell initPickerWithArray:[CoreDataUtils getSearchBrands]];
			[cell setPickerSelectAt:[condition valueForKey:@"Brand"]];
			break;
		case 4:
		{
			UISwitch *_switch = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 100, 30)];
			[cell addSubview:_switch];
			[_switch release];
			[_switch addTarget:self action:@selector(switchChange:) forControlEvents:UIControlEventValueChanged];
			cell.titleLabel.text = @"On Promo";
			_switch.on = [[condition objectForKey:@"OnPromo"] boolValue];
			cell.textField.hidden = YES;
			break;
		}
			
		case 5:
		{
			cell.titleLabel.text = @"By Price";
			[cell initPickerWithArray:[CoreDataUtils getSearchPriceType]];
			[cell setPickerSelectAt:[condition valueForKey:@"PriceType"]];
			break;
		}
		case 6:
			cell.titleLabel.text = [[condition valueForKey:@"PriceType"] isEqualToString:@"2"] ? @"From" : @"Price";
			cell.textField.text = [[condition valueForKey:@"PriceValue1"] stringValue];
			cell.textField.keyboardType = UIKeyboardTypeNumberPad;
			break;
		case 7:
			cell.titleLabel.text = @"To";			
			cell.textField.text = [[condition valueForKey:@"PriceValue2"] stringValue];
			cell.textField.keyboardType = UIKeyboardTypeNumberPad;
			break;
		default:
			cell.titleLabel.text = @"AAAAA";
			break;
	}
	return cell;
}

-(void) switchChange:(id) sender
{
	[condition setObject:[NSNumber numberWithBool:((UISwitch*)sender).on] forKey:@"OnPromo"];
}

-(void) textFieldDidBeginEditing:(UITableViewCell*)cell
{
	_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, 380 - 216 + 35);
	[_tableView scrollRectToVisible:cell.frame animated:YES];
}

-(void) textFieldDidEndEditing:(UITableViewCell*)cell
{
	
	switch (cell.tag) {
		case 0:
			[condition setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:@"Shop"];
			break;
		case 1:
			[condition setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:@"MainCategory"];
			[_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
			break;
		case 2:
			[condition setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:@"SubCategory"];
			break;
		case 3:
			[condition setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:@"Brand"];
			break;
		case 5:
			[condition setObject:[((TitleTextfieldCell*)cell) cellValue] forKey:@"PriceType"];
			_tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, 380);
			[_tableView reloadData];
			break;
		default:
			break;
	}
}

-(IBAction)openSearchResult:(id) sender
{
	//todo
	SearchResultViewController *custom = [[SearchResultViewController alloc] initWithNibName:@"SearchResultViewController" bundle: nil];
	[self.navigationController pushViewController:custom animated:YES];
	[custom release];
}

-(IBAction) homePress:(id) sender
{
	//[self.parentViewController dismissModalViewControllerAnimated:YES];
	[self.parentViewController dismissModalViewControllerAnimated:NO];
}

- (IBAction)scanPressed:(id)sender {
	
	ZXingWidgetController *widController = [[ZXingWidgetController alloc] initWithDelegate:self showCancel:YES OneDMode:NO];
	QRCodeReader* qrcodeReader = [[QRCodeReader alloc] init];
	NSSet *readers = [[NSSet alloc ] initWithObjects:qrcodeReader,nil];
	[qrcodeReader release];
	widController.readers = readers;
	[readers release];
	NSBundle *mainBundle = [NSBundle mainBundle];
	widController.soundToPlay =
	[NSURL fileURLWithPath:[mainBundle pathForResource:@"beep-beep" ofType:@"aiff"] isDirectory:NO];
	[self presentModalViewController:widController animated:YES];
	[widController release];
}

#pragma mark -
#pragma mark ZXingDelegateMethods

- (void)zxingController:(ZXingWidgetController*)controller didScanResult:(NSString *)result {
	
	[self dismissModalViewControllerAnimated:NO];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:result message:result delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (void)zxingControllerDidCancel:(ZXingWidgetController*)controller {
	[self dismissModalViewControllerAnimated:YES];
}

@end
